<script setup>
import { ref, defineEmits,computed,onMounted} from "vue";
import { useRoute,useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
import { ElMessage, ElMessageBox } from "element-plus";
import { ElDialog } from "element-plus";
import axios from "axios";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from "@element-plus/icons-vue";
const dialogVisible = ref(false);
const dialogVisible2 = ref(false); // 控制对话框显示与隐藏
const addDeptVisible = ref(false);
const searchQuery = ref("");
const showList = ref([]);


const input = ref(""); // 绑定输入框的内容


const formData = ref({
  id:"",
  username: "",
  password:"",
  gender: "",
  address: "",
  email: "",
  deleted:"",
});
const updateData = ref({
  id: "",
  username: "",
  password:"",
  gender: "",
  address: "",
  email: "",
  deleted:"",
});
const pages = ref(1);
const size = ref(5);
const background = ref(true);
const disabled = ref(false);
const total = ref();
const pagerCount = ref(7);
const username=ref();
const handleSizeChange = (size) => {
  size.value = size;
  if (input.value == "") {
    search();
  } else {
    searchData();
  }
};
// 处理当前页变化
const handleCurrentChange = (page) => {
  pages.value = page;
  if (input.value == "") {
    search();
  } else {
    searchData();
  }
};
onMounted(() => {
  search()
})

const search = () => {
  axios
    .get("http://10.7.183.87:8080/page", {
    params: { pageNum: pages.value, pageSize: size.value ,username:username.value},
    })
    .then((response) => {
        console.log(response.data)
      showList.value = response.data.records;
      total.value = response.data.total;
    })
    .catch((error) => {
      console.error("There was an error making the request:", error);
    });
};

const deleted = (row) => {
  ElMessageBox.confirm("你确定删除用户吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      
      axios
        .get(`http://10.7.183.87:8080/lq/user/${row.id}`)
        .then((response) => {
          // 假设后台返回成功
          row.deleted = 1;
          ElMessage({
            type: "success",
            message: "修改成功！",
          });
        })
        .catch((error) => {
          ElMessage({
            type: "error",
            message: "修改失败！",
          });
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消修改",
      });
    });
};

const addUser = () => {
  dialogVisible.value = true;
};
const closeDialog = () => {
  dialogVisible.value = false;
};
const closeDialog3 = () => {
  addDeptVisible.value = false;
};
// 提交表单
const submitForm = () => {
  axios
    .post("http://10.7.183.87:8080/lq/user", formData.value)
    .then((response) => {
      // 请求成功，检查返回的状态码或其他字段
      if (response.status === 200) {
        console.log("请求成功", response.data);
        dialogVisible.value = false;
        ElMessage.success("添加成功");
        search();

        formData.value.username = "";
        formData.value.password = "";
        formData.value.gender = "";
        formData.value.email = "";
        formData.value.address = "";
        formData.value.deleted = "";

        // 在这里可以做成功后的处理，比如显示提示信息、更新 UI 等
      } else {
        console.log("请求失败,返回非200状态码");
      }
    })
    .catch((error) => {
      // 请求失败的处理
      console.error("请求出错：", error);
      // 可以根据具体错误进行处理，比如提示用户网络错误等
    });
};

const update = (row) => {
  dialogVisible2.value = true;
  axios
    .get(`http://10.7.183.87:8080/selectById/${row.id}`)
    .then((response) => {
      updateData.value = response.data.data;
    });
};

// 关闭对话框
const closeDialog2 = () => {
  dialogVisible2.value = false;
};

const submitForm2 = () => {
  axios
    .post("http://10.7.183.87:8080/update", updateData.value)
    .then((response) => {
      // 处理成功的响应
      // 可根据返回数据更新 UI 或进行其他操作
      dialogVisible2.value = false; // 关闭对话框
      ElMessage.success("更新成功");
      search();
    })
    .catch((error) => {
      // 处理错误
      ElMessageBox.error("更新失败");
      // 可在此提示用户失败原因或进行错误处理
    });
};

const visible = ref(false); // 控制弹窗显示
const isLoggedIn = ref(true); // 控制登录状态

// 显示退出确认弹窗
const showLogoutDialog = () => {
  visible.value = true;
};

// 取消退出，关闭弹窗
const cancelLogout = () => {
  visible.value = false;
};

// 确定退出，执行退出操作
const confirmLogout = () => {
  // 执行退出操作（如清除 token、跳转等）
    
    // 请求成功后执行
    ElMessageBox.alert("退出成功");
router.push({
        path: '/login',
  })
};

// 弹窗关闭时重置状态
const resetDialog = () => {
  visible.value = false;
};

// 跳转到登录页面的逻辑
const showLoginPage = () => {
  // 这里你可以实现跳转到登录页面的逻辑
  ElMessageBox.alert("登录成功");
  isLoggedIn.value = true;
};

const filteredList = computed(() => {
      return showList.value.filter(item => item.deleted === 0);
    });

</script>

<template>
  <div>
    <el-header class="header">
      <div class="header-container">
        <!-- Logo -->
        <div class="logo">几组</div>
        <!-- 搜索框 -->
        <el-input
          v-model="username"
          style="width: 200px; margin-left: 30px"
          placeholder="请输入关键字搜索"
          class="search-box"
        />
        <el-button :icon="Search" circle @click="search" />
        <!-- 用户操作区域 -->
        <div class="user-actions">
          <el-button type="primary" @click="addUser">添加用户</el-button>
          <el-button type="primary" @click="showLogoutDialog" v-if="isLoggedIn"
            >退出系统</el-button
          >
          <el-button type="primary" @click="showLoginPage" v-else
            >登录</el-button
          >
          <el-dialog
            v-model="visible"
            title="确定退出系统吗"
            @close="resetDialog"
            width="500px"
            height="300px"
          >
            <span slot="footer" class="dialog-footer">
              <el-button @click="cancelLogout">取消</el-button>
              <el-button type="primary" @click="confirmLogout">确定</el-button>
            </span>
          </el-dialog>
        </div>
      </div>
    </el-header>
    
    <el-table :data="filteredList" style="width: 90%; margin-left: 50px">
      <el-table-column prop="id" label="编号" width="220" />
      <el-table-column prop="username" label="名字" width="220" />
      <el-table-column prop="gender" label="性别" width="220"/>
      <el-table-column prop="address" label="地址" width="230" />
      <el-table-column prop="email" label="邮箱" width="300">
      </el-table-column>

      <el-table-column label="操作" width="170">
        <template #default="{ row }">
          <el-button type="success" @click="update(row)">更新</el-button>
          <el-button type="danger" @click="deleted(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加用户" v-model="dialogVisible" width="500px">
      <!-- 表单内容 -->
      <el-form :model="formData" label-width="auto" style="width: 400px">
    
        <el-form-item label="姓名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入姓名" />
        </el-form-item>

         <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-input v-model="formData.gender" placeholder="请输入性别" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="更新信息" v-model="dialogVisible2" width="500px">
      <el-form :model="updateData" label-width="auto" style="width: 400px">
        

        <el-form-item label="姓名" prop="username">
          <el-input v-model="updateData.username" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-input v-model="updateData.gender" placeholder="请输入性别" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="updateData.address" placeholder="请输入地址" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateData.email" placeholder="请输入邮箱" />
        </el-form-item>

         <el-form-item label="密码" prop="password">
          <el-input v-model="updateData.password" placeholder="请输入密码" />
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog2">取消</el-button>
        <el-button type="primary" @click="submitForm2">确定</el-button>
      </span>
    </el-dialog>

     <el-pagination
      class="page"
      :currentPage="pages"
      :page-size="size"
      :disabled="disabled"
      :background="background"
      :total="total"
      :pager-count="pagerCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="prev, pager, next"
    />
  </div>
  
</template>

<style scoped>
.header {
  background-color: #f5f5f5;
  padding: 10px 20px;
}

.header-container {
  display: flex;
  width: 100%;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  margin-top: 6px;
}

.search-box {
  margin-right: 10px;
}

.user-actions {
  display: flex;
  gap: 10px; /* 设置按钮之间的间距 */
  margin-left: 900px;
}

.dialog-footer {
  margin-left: 270px;
}
.page {
  margin-left: 650px;
  margin-top: 30px;
}
</style>